<?php

/**
 * 处理图片
 * @author Bruce
 * @date 2015-07-17
 */
namespace apps\common\controllers;
if( ! APP_ROOT  ) return 'Direct Access Deny!';

use apps\common\libraries\Uploader;
use apps\common\libraries\OssServer;
use apps\common\models\ImgAssets;
use enums\DBEnums;;
use helpers\TimeUtils;
use enums\ImgBizEnums;

use apps\common\libraries\ImageCrop;
use helpers\CommUtils;

class UploadController extends \Phalcon\Mvc\Controller
{

    private $configEditor;
    
    public function initialize()
    {
        $userInfo = $this->session->get( 'userInfo' ); //管理
        //$memInfo = $this->session->get( 'memInfo' );//会员
        //$museumInfo = $this->session->get( 'museumInfo' );//会员
        if( empty( $userInfo ) )
        {
            if( ! $this->request->isAjax() )
            {
                return $this->dispatcher->forward( array( 'controller' => 'error', 'action' => 'toLogin' ));
            }
            else
            {
                 echo json_encode( [ 'state' => '必须登录后才能上传文件！' ]);
                 return;
            }
        }
        
//         $this->configEditor = include_once APP_ROOT . 'config/ueditor.php';
        $this->configEditor = $this->di['ueditorCfg'];//include_once APP_ROOT . 'config/ueditor.php';
        
    }

    private function upload( $CONFIG )
    {
        /* 上传配置 */
        $base64 = "upload";
        switch (htmlspecialchars($_GET['action'])) 
        {
        	case 'uploadimage':
        	    $config = array(
            	    "pathFormat" => $CONFIG['imagePathFormat'],
            	    "maxSize" => $CONFIG['imageMaxSize'],
            	    "allowFiles" => $CONFIG['imageAllowFiles']
        	    );
        	    $fieldName = $CONFIG['imageFieldName'];
        	    break;
        	case 'uploadscrawl':
        	    $config = array(
        	    "pathFormat" => $CONFIG['scrawlPathFormat'],
        	    "maxSize" => $CONFIG['scrawlMaxSize'],
        	    "allowFiles" => $CONFIG['scrawlAllowFiles'],
        	    "oriName" => "scrawl.png"
        	            );
        	            $fieldName = $CONFIG['scrawlFieldName'];
        	            $base64 = "base64";
        	            break;
        	case 'uploadvideo':
        	    $config = array(
        	    "pathFormat" => $CONFIG['videoPathFormat'],
        	    "maxSize" => $CONFIG['videoMaxSize'],
        	    "allowFiles" => $CONFIG['videoAllowFiles']
        	    );
        	    $fieldName = $CONFIG['videoFieldName'];
        	    break;
        	case 'uploadfile':
        	default:
        	    $config = array(
        	    "pathFormat" => $CONFIG['filePathFormat'],
        	    "maxSize" => $CONFIG['fileMaxSize'],
        	    "allowFiles" => $CONFIG['fileAllowFiles']
        	    );
        	    $fieldName = $CONFIG['fileFieldName'];
        	    break;
        }
        
        /* 生成上传实例对象并完成上传 */
        $up = new Uploader( $fieldName, $config, $base64, $this->di  );
        
        /**
         * 得到上传文件所对应的各个参数,数组结构
         * array(
         *     "state" => "",          //上传状态，上传成功时必须返回"SUCCESS"
         *     "url" => "",            //返回的地址
         *     "title" => "",          //新文件名
         *     "original" => "",       //原始文件名
         *     "type" => ""            //文件类型
         *     "size" => "",           //文件大小
         * )
        */
        
        /* 返回数据 */
        return json_encode($up->getFileInfo());
    }
    
    private function listFiles( $CONFIG )
    {
        if( !$this->session->get( 'memInfo' ) && !$this->session->get( 'userInfo' ) )
        {
            echo json_encode( [ 'state' => '必须登录后才能上传文件！' ]);
            return;
        }
        
        /* 判断类型 */
        switch ($_GET['action']) {
            /* 列出文件 */
        	case 'listfile':
        	    $allowFiles = $CONFIG['fileManagerAllowFiles'];
        	    $listSize = $CONFIG['fileManagerListSize'];
        
        	    break;
        	    /* 列出图片 */
        	case 'listimage':
        	default:
        	    $allowFiles = $CONFIG['imageManagerAllowFiles'];
        	    $listSize = $CONFIG['imageManagerListSize'];
        }
        $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);
        
        /* 获取参数 */
        $size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize;
        $start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0;
//         $end = $start + $size;
        
        /* 获取文件列表 */
        if( $this->configEditor->type )
        {
            $files = $this->getFilesRecFromMongDB( $size, false );
        }
        else 
        {
        	$files = $this->getFilesRec( $CONFIG );
        }
            
        if (!count($files)) {
            return json_encode(array(
                    "state" => "no match file",
                    "list" => array(),
                    "start" => $start,
                    "total" => count($files)
            ));
        }
        
        $list = array();
        foreach( $files as $v )
        {
            $list[] = array( 'url' => $v['url'], 'mtime' => $v[ 'createtime' ] );
        }
        
        
        /* 返回数据 */
        $result = json_encode(array(
                "state" => "SUCCESS",
                "list" => $list,
                "start" => $start,
                "total" => count($list)
        ));
        
        return $result;
    }
    
    /**
     * 遍历获取目录下的指定类型的文件
     * @param $path
     * @param array $files
     * @return array
     */
    private function getFilesRecFromMongDB( $iSize = 0, $bFS = true )
    {
        $uid = 0;
        
        switch( $_GET['bizt'] )
        {
        	case 'mem':
        	    $memInfo = $this->session->get( 'memInfo' );
        	    if( $memInfo )
        	        $uid = $memInfo['mem_id'];
        	    
        	    if( $bFS )
        	        $mem = $this->mongodb->selectCollection( 'fs_mem' );
        	    else 
    	           $mem = $this->mongodb->selectCollection( 'fastdfs_mem' );
        	    
    	        if( !$iSize )
    	            return iterator_to_array( $mem->find( array( 'uid' => $uid ))->sort( array( 'createtime' => -1 ) ));
    	        else
    	            return iterator_to_array( $mem->find( array( 'uid' => $uid ))->sort( array( 'createtime' => -1 ) )->limit( $iSize ));
        	    
        	case 'shop':
        	    $userInfo = $this->session->get( 'userInfo' );
        	    if( $userInfo )
        	        $uid = $userInfo['shop_id'];
        	    
        	    if( $bFS )
        	        $shop = $this->mongodb->selectCollection( 'fs_shop' );
        	    else
        	        $shop = $this->mongodb->selectCollection( 'fastdfs_shop' );
    	        
    	        if( !$iSize )
    	            return iterator_to_array( $shop->find( array( 'uid' => $uid ))->sort( array( 'createtime' => -1 ) ));
    	        else
    	            return iterator_to_array( $shop->find( array( 'uid' => $uid ))->sort( array( 'createtime' => -1 ) )->limit( $iSize ));
        	        	
        	case 'user':
        	    $userInfo = $this->session->get( 'userInfo' );
        	    if( $userInfo )
        	        $uid = $userInfo['id'];
        	    
        	    if( $bFS )
        	        $user = $this->mongodb->selectCollection( 'fs_user' );
        	    else
        	        $user = $this->mongodb->selectCollection( 'fastdfs_user' );
        	    
    	        if( !$iSize )
    	            return iterator_to_array( $user->find( array( 'uid' => $uid ))->sort( array( 'createtime' => -1 ) ));
    	        else
    	            return iterator_to_array( $user->find( array( 'uid' => $uid ))->sort( array( 'createtime' => -1 ) )->limit( $iSize ));
            case 'museun':
                $museunInfo = $this->session->get( 'museunInfo' );
                if( $museunInfo )
                    $uid = $museunInfo['id'];
                 
                if( $bFS )
                    $museum = $this->mongodb->selectCollection( 'fs_museum' );
                else
                    $museum = $this->mongodb->selectCollection( 'fastdfs_museum' );
                         
                if( !$iSize )
                  return iterator_to_array( $user->find( array( 'uid' => $uid ))->sort( array( 'createtime' => -1 ) ));
                else
                  return iterator_to_array( $user->find( array( 'uid' => $uid ))->sort( array( 'createtime' => -1 ) )->limit( $iSize ));
        	default:
        	    return null;
        }
    
    }
    
     /**
     * 遍历获取目录下的指定类型的文件
     * @param $path
     * @param array $files
     * @return array
     */
    private function getFilesRec( $CONFIG )
    {
        $uid = 0;
        
        switch( $_GET['bizt'] )
        {
        	case 'mem':
        	    $memInfo = $this->session->get( 'memInfo' );
        	    if( $memInfo )
        	        $uid = $memInfo['mem_id'];
        	    break;
        	case 'shop':
        	    $userInfo = $this->session->get( 'userInfo' );
        	    if( $userInfo )
        	        $uid = $userInfo['shop_id'];
                break;
        	case 'user':
        	    $userInfo = $this->session->get( 'userInfo' );
        	    if( $userInfo )
        	        $uid = $userInfo['id'];
                break;
            case 'museum':
                $museumInfo = $this->session->get( 'museumInfo' );
                if( $museumInfo )
                    $uid = $museumInfo['id'];
                    break;
            default:
        	    return null;
        }
        
        /* 判断类型 */
    switch ($_GET['action']) {
        /* 列出文件 */
        case 'listfile':
            $allowFiles = $CONFIG['fileManagerAllowFiles'];
            $listSize = $CONFIG['fileManagerListSize'];

             $path = $CONFIG['fileManagerListPath'];
             $path = str_replace( "{uid}", $uid, $CONFIG['fileManagerListPath'] );
             $path = str_replace( "{bizt}", $_GET[ 'bizt' ], $path );
            break;
        /* 列出图片 */
        case 'listimage':
        default:
            $allowFiles = $CONFIG['imageManagerAllowFiles'];
            $listSize = $CONFIG['imageManagerListSize'];

            $path = $CONFIG['imageManagerListPath'];
            $path = str_replace( "{uid}", $uid, $CONFIG['imageManagerListPath'] );
            $path = str_replace( "{bizt}", $_GET[ 'bizt' ], $path );
    }
            

        $rootPath =  $_SERVER['DOCUMENT_ROOT'];
        if( strpos( $rootPath, 'public' ) === false )
            $rootPath .= '/public';
        
        $path =  $rootPath . (substr($path, 0, 1) == "/" ? "":"/") . $path;

        $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);
        $files = $this->getFilesForFS( $path, $allowFiles);
        
        return $files;
    }
    
     /**
      * 遍历获取目录下的指定类型的文件
      * @param $path
      * @param array $files
      * @return array
      */
     private function getFilesForFS($path, $allowFiles, &$files = array())
     {
         if (!is_dir($path)) return null;
         if(substr($path, strlen($path) - 1) != '/') $path .= '/';
         $handle = opendir($path);
         while (false !== ($file = readdir($handle))) {
             if ($file != '.' && $file != '..') {
                 $path2 = $path . $file;
                 if (is_dir($path2)) {
                     $this->getFilesForFS($path2, $allowFiles, $files);
                 } else {
                     if (preg_match("/\.(".$allowFiles.")$/i", $file)) {
                            $rootPath = $_SERVER['DOCUMENT_ROOT'];
                            if( strpos( $rootPath, 'public' ) === false )
                            {
                                $rootPath .= '/public';
                            }
                             $files[] = array(
                                 'url'=> substr( $path2, strlen( APP_ROOT . 'public' ) ),
                                 'createtime'=> filemtime($path2)
                         );
                     }
                 }
             }
         }
         return $files;
     }
     
     /**
      * oss 上传图片回掉函数
      * @return boolean
      */
    public function cbOssAction()
    {
        $objRet = new \stdClass();
        if( !$_POST )
        {
            $objRet->state = 'ERROR';
            $objRet->msg = '回调参数异常';
            
            return json_encode( $objRet );
        } 
        
        $currBucket = $this->configEditor['oss_server']['cur'];
        $currBucketName = $this->configEditor['oss_server']['paths'][$currBucket]['OSS_BUCKET_NAME'];
        $imgs = new ImgAssets();
        $imgs->delsign      = DBEnums::DELSIGN_NO;
        $imgs->addtime  = TimeUtils::getFullTime();
        $imgs->filename     = basename($_POST['filename']);
        $imgs->size         = $_POST['size'];
        $imgs->type         = $_POST['mimeType'];
        $imgs->bucket       = $currBucketName;
        $imgs->object       = $_POST['filename'];
        $imgs->height       = $_POST[ 'height' ];
        $imgs->width        = $_POST[ 'width' ];
        
        if( isset( $_POST ) && isset( $_POST[ 'biz_type' ] ) )
        {
            $imgs->biz_type = $_POST[ 'biz_type' ];
        }
        //mem_id/user_id
        if( isset( $_POST ) && isset( $_POST[ 'mem_id' ] ) )
        {
            $imgs->mem_id = $_POST[ 'mem_id' ];
        }
        if( isset( $_POST ) && isset( $_POST[ 'mem_type' ] ) )
        {
            $imgs->mem_type = $_POST[ 'mem_type' ];
        }
        
        if( $imgs->save() )
        {
            $objRet->state = 'SUCCESS';
            $objRet->assetsid = $imgs->id;
            $objRet->bucket   = $imgs->bucket;
            $objRet->object   = $imgs->object;
            $objRet->url      = $this['urlCfg']->url->cdn_oss_img.'/'.$_POST['filename'];
            $objRet->title    = basename($_POST['filename']);
            $objRet->original =  basename($_POST['filename']);
            $objRet->type     = $_POST['mimeType'];
            $objRet->size     = $_POST['size'];
            $objRet->height     = $imgs->width;
            $objRet->width     = $imgs->width;
        }
        else
        {
            $objRet->state = 'SUCCESS';
            $objRet->msg = '写入资源库中失败.';
            $objRet->url = $this['urlCfg']->url->cdn_oss_img . '/'.$_POST['filename'];
            $objRet->title = basename($_POST['filename']);
            $objRet->original =  basename($_POST['filename']);
            $objRet->type = $_POST['mimeType'];
            $objRet->size = $_POST['size'];
            $objRet->height = $_POST[ 'height' ];
            $objRet->width  = $_POST[ 'width' ];
        }
        
        echo json_encode( $objRet );
    } 
     
    /**
     * oss + ueditor 多图上传
     * @param unknown $jscfg    格式化 - 配置项
     * @param unknown $osscfg   oss服务配置
     * @param unknown $param    地址栏参数
     * @return boolean
     */
    private function ossUploadFile( $jscfg, $osscfg, $param )
    {
        if( !$jscfg || !$osscfg || !$param )
            return false;
        
        $objParams = json_decode( $param );
        $osscfg[ 'bizt' ] = $objParams->mem_type;
        
        $oss_server = new OssServer( $osscfg );
        $oss_config = $oss_server->get_config( $objParams, $osscfg[ 'OSS_CALLBACK_URL' ] );
        
        $oss_uconf = [
            'imageUpload2Oss'=>true,
            'imageUpload2OssActionUrl' => $oss_config[ 'host' ],
            'imageUpload2OssFormData' => [
                'key' => $objParams->mem_type. '/{yyyy}{mm}{dd}/'.'${random}', //文件命名规则, ${filename}以原文件名  ${random}随机文件名
                'policy' => $oss_config['policy'],
                'OSSAccessKeyId' => $oss_config[ 'accessid' ],
                'success_action_status' => '200',
                'Signature' => $oss_config[ 'signature' ]
            ],
            //重写OSS接受文件字段名
            'imageFieldName' => 'file'
        ];
        
        if( $osscfg[ 'OSS_CALLBACK_URL' ] )
        {
            $oss_uconf[ 'imageUpload2OssFormData' ][ 'callback' ] = $oss_config[ 'callback' ];
        }
        //TODO, 是否有回调配置
        $result = array_merge( $jscfg, $oss_uconf );
        return $result; //最终$CONFIG
    }
    
    /**
     * mobile 前端简单上传
     */
    public function plupAction()
    {
        /**
         *  url 传递参数组
         *  mem_type        操作者类型       ---- mem/narrator/museum/admin
         *  mem_id          操作者                ---- id
         *  biz_type        图片业务类型    ---- ImgBizEnums
         */
        
        $arrUrlParams = $this->dispatcher->getParams();
        $files = $_FILES;
        
//         if( $this->session->has( 'memInfo' ) && !empty( $this->session->get( 'memInfo' ) ) )
//         {//登录
//             /**
//              * 若 :
//              * 用户登录但挟带标记与session中存储不同
//              * 则使用session中的标记重置挟带的标记
//              */
//             $memInfo = $this->session->get( 'memInfo' );
//             $signId = $memInfo[ 'id' ];
//             if( $signId != $arrUrlParams[ 'mem_id' ] )
//             {
//                 $arrUrlParams[ 'mem_id' ] = $signId;
//             }
//             $session_name = $arrUrlParams[ 'mem_type' ] . '_' . $signId . '_' . $arrUrlParams[ 'biz_type' ] . '_count';
//         }
//         else
//         {//未登录
//             $session_name = $arrUrlParams[ 'biz_type' ] . '_count';
//         }
//         $iUploadTimes = $this->session->get( $session_name )?$this->session->get( $session_name ):0;
//         $this->session->set( $session_name , ++$iUploadTimes );
        
        $params = json_encode( $arrUrlParams );
        $driver = $this->configEditor['type'];
        switch ( $driver )
        {
            case 'fs':
            break;
            case 'fastdfs':
            break;
            case 'oss_server':
                $objRetImg = $this->_plUpload( $arrUrlParams, $files );
            break;
        }
        
        return json_encode( $objRetImg );
        
    }
    
    
    /**
     * plupload 方式上传图片至oss
     * @param unknown $arrParams
     */
    private function _plUpload( $arrParams, $files )
    {
    	if( !$arrParams || empty( $arrParams ) || !$files || empty( $files ) )
    		return false;
    	 
    	//存在截取图片大小的限制
    	if( isset( $arrParams[ 'biz_img_size' ] ) )
    	{
    		$iLimitWidth = 0;
    		$iLimitHeight = 0;
    		$arrSize = explode( 'x' , $arrParams[ 'biz_img_size' ] );
    		if( $arrSize && !empty( $arrSize ) )
    		{
    			$iLimitWidth = $arrSize[ 0 ];
    			$iLimitHeight = $arrSize[ 1 ];
    		}
    		if( 0 != $iLimitWidth && 0 != $iLimitHeight  )
    		{
    			try{
    				$cutImgObj = new ImageCrop( $files['file'][ 'tmp_name' ], $files['file'][ 'tmp_name' ] );
    				$cutImgObj->Crop( $iLimitWidth, $iLimitHeight, ImageCrop::IMG_MODE_CUT );
    				$cutImgObj->SaveImage();
    				$cutImgObj->SaveAlpha();
    				$cutImgObj->destory();
    			}
    			catch ( \Exception $e )
    			{
    				$this->errLog->error( $this->appVerCfg->appVersion . '|' .
    						$this->router->getModuleName() .'|'  . __METHOD__  . '|' .
    						__LINE__. '|' . 'plupload 裁剪图片异常：参数为：' . var_export( $arrParams, true ) . ', 图片信息为：' . var_export( $files, true ) .' ,异常信息为:' . $e->getMessage() );
    				
    			}
    		}
    	}
    	 
    	//获取上传图片信息
    	$arrImgInfo = $this->_getImageInfo( $files['file'][ 'tmp_name' ] );
    	if( !$arrImgInfo || empty( $arrImgInfo  )  )
    	{
    		return false;
    	}
    	
    	$driver = $this->configEditor['type'];
    	$curBrcket = $this->configEditor[$driver]['cur'];
    	$arrCfg = $this->configEditor[$driver]['paths'][$curBrcket];
    	 
    	$strOssObject = $arrParams[ 'mem_type' ] . '/' . date( 'Y-m-j', $_SERVER[ 'REQUEST_TIME' ] );
    	//将图片上传至 oss
    	$iOss = $this->ossCfg->cur;
    	$currBucket = $this->ossCfg->paths->{$iOss}->OSS_BUCKET_NAME;
    	$strOssKey = $this->ossCfg->paths->{$iOss}->OSS_ACCESS_KEY;
    	 
    	// 上传至oss服务器
    	try{
    		$strPicName = CommUtils::getUNID() . $arrImgInfo[ 'suffx'  ];
    		$jsonResponse =  $this->oss->uploadFile( $currBucket, $strOssObject . '/' . $strPicName, $files['file'][ 'tmp_name' ] );
    	}
    	catch( \Exception $e  )
    	{
    		$this->errLog->error( $this->appVerCfg->appVersion . '|' .
    				$this->router->getModuleName() .'|'  . __METHOD__  . '|' .
    				__LINE__. '|' . 'plupload 上传图片至 OSS 异常：参数为：' . var_export( $arrParams, true ) . ', 图片信息为：' . var_export( $files, true ) .' ,异常信息为:' . $e->getMessage() );
    		
    		return false;
    	}
    	if( !is_null( $jsonResponse  ) || !empty( $jsonResponse  ) )
    	{
    		return false;
    	}
    	//业务类型
    	$biz_type = $arrParams[ 'biz_type' ];
    	//会员标记
    	if( isset( $arrParams[ 'mem_id' ] ) )
    	{
    		$mem_id = $arrParams[ 'mem_id' ];
    	}
    	else
    	{
    		$mem_id = 0;
    	}
    	$arrImg[ 'filename'  ] = $strPicName;
    	$arrImg[ 'size'  ] = $arrImgInfo[ 'size' ];
    	$arrImg[ 'bucket'  ] = $currBucket;
    	$arrImg[ 'object'  ] = $strOssObject . '/' . $strPicName;
    	$arrImg[ 'img_type'  ] = $arrImgInfo[ 'mime'  ];
    	 
    	switch ( $arrParams[ 'biz_prefix' ] )
    	{
//     		case ImgBizEnums::MUSEUM_AVATAR_PREFIX:
//     			$table = new MuseumAvatarPics();
//     			break;
//     		case ImgBizEnums::MUSEUM_PRODUTC_PREFIX:
//     			$table = new MuseumProductPics();
//     			break;
//     		case ImgBizEnums::MUSEUM_APPLY_PREFIX:
//     			$table = new MuseumApplyPics();
//     			break;
    	}
    	 
    	try{
    		$arrRes = $table->addImgs( $arrImg, $biz_type, $mem_id );
    		if( !$arrRes || false == $arrRes )
    		{
    			return false;
    		}
    		else
    		{
    			$data[ 'imgid' ] = $arrRes[ 'id' ];
    			$data[ 'url' ] = $arrRes[ 'cdn_url' ]  . '/' . $arrRes[ 'object' ];
    			 
    			return $data;
    		}
    	}
    	catch( \Exception $e )
    	{
    		$this->errLog->error( $this->appVerCfg->appVersion . '|' .
    				$this->router->getModuleName() .'|'  . __METHOD__  . '|' .
    				__LINE__. '|' . 'plupload 上传图写入资源库失败：参数为：' . var_export( $arrParams, true ) . ', 图片信息为：' . var_export( $files, true ) .' ,异常信息为:' . $e->getMessage() );
    	}
    	 
    }
    
    /**
     * 获取图片信息
     * @param unknown $img
     * @return boolean|multitype:unknown string int
     */
    private function _getImageInfo( $img )
    {
    	if( !$img )
    	{
    		return false;
    	}
    	
    	$img_info = getimagesize( $img );
    	if( !$img_info || empty( $img_info ) )
    		return false;
    	 
    	switch( intval( $img_info[2] ) )
    	{
    		case 1:
    			$suffx = '.gif';
    			break;
    		case 3:
    			$suffx = '.png';
    			break;
    		default:
    			$suffx = '.jpg';
    			break;
    	}
    	// 获取图片大小
    	$img_size = filesize($img);
    
    	$new_img_info = array (
    			'width' =>$img_info[0],
    			'height'=>$img_info[1],
    			'suffx' => $suffx,
    			'size' =>$img_size,
    			'mime' =>$img_info['mime'],
    	);
    
    	return $new_img_info;
    }
    
    /**
     * UE 上传
     */
    public function ctrlAction()
    {
        date_default_timezone_set( "Asia/shanghai" );
        $ueditorCfg = json_decode( preg_replace( "/\/\*[\s\S]+?\*\//", "",  file_get_contents( APP_ROOT . 'config' .DIRECTORY_SEPARATOR . APP_MODE . DIRECTORY_SEPARATOR . 'ueditor.json' ) ), true );

        // OSS + Ueditor 作为存储库上传图片至阿里云OSS
        /*
         *
         * 根据 bizt_type 判断上传图片个数
         * biz_type_count 未登录 1 ~5
         * mem_type + mem_id + biz_type_count  登录  1~10
         * ---------------------------------------------------------------------------------------
         */
        /**
         *  url 传递参数组
         *  mem_type        操作者类型       ---- mem/narrator/museum/admin
         *  mem_id          操作者                ---- id
         *  biz_type        图片业务类型    ---- ImgBizEnums
         */
        $arrUrlParams = $this->dispatcher->getParams();
        
        $action = $_GET[ 'action' ];
        
        switch( $action )
        {
            case 'config':
                $params = json_encode( $arrUrlParams );
                $driver = $this->configEditor['type'];
                switch ( $driver )
                {
                    case 'fs':
                        $arrCfg = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", 
                            file_get_contents( APP_ROOT . 'config/' . APP_MODE . '/ueditorFSConfig.json' )), true);
                        
                        $result = json_encode( $arrCfg );
                    break;
                    case 'fastdfs':
                    break;
                    case 'oss_server':
                        $curBrcket = $this->configEditor[$driver]['cur'];
                        $arrCfg = $this->configEditor[$driver]['paths'][$curBrcket];
                        $arrConfig = $this->ossUploadFile( $ueditorCfg, $arrCfg, $params );
                        $result = '(' . json_encode( $arrConfig ) . ')';
                    break;
                }
            break;
            /* 上传图片 */
            case 'uploadimage':
                $this->checkImage();
            /* 上传涂鸦 */
            case 'uploadscrawl':
            /* 上传视频 */
            case 'uploadvideo':
            /* 上传文件 */
            case 'uploadfile':
                $this->di['ueditorCfg'];
//                 $result = include ( "action_upload.php" );
                $result = $this->upload( $ueditorCfg );
                break;
            /* 列出图片 */
            case 'listimage':
            // $result = include("action_list.php");
            // break;
            /* 列出文件 */
            case 'listfile':
//                 $result = include ( "action_list.php" );
                $result = $this->listFiles( $ueditorCfg );
                
                break;
            /* 抓取远程文件 */
            case 'catchimage':
                $result = include ( "action_crawler.php" );
                break;
            default:
                $result = json_encode( 
                        array(
                                'state' => '请求地址出错'
                        ) );
                break;
        }
        /* 输出结果 */
        if( isset( $_GET[ "callback" ] ) )
        {
            if( preg_match( "/^[\w_]+$/", $_GET[ "callback" ] ) )
            {
                echo htmlspecialchars( $_GET[ "callback" ] ) . '(' . $result .  ')';
            }
            else
            {
                echo json_encode( array( 'state' => 'callback参数不合法' ) );
            }
        }
        else
        {
            echo $result  ;
        }
    }
    
    
    /**
     * 删除图片
     *    -- 存在删除按钮点击触发 异步删除
     * @return string
     */
    public function delimgAction()
    {
    	//------------
    	// 要操作的 id
    	//  用户则为该用户id  会员则为该会员id
    	//------------
    	$type = $this->request->getPost( 'type', 'trim' );
    	$operation = $this->request->getPost( 'operation', 'int' );
    	
    	$optid = $this->request->getPost( 'id', 'int' );
    	$objRet = new \stdClass();
    	if( !$optid || !$operation )
    	{
    	    $objRet = new \stdClass();
    	    
    		$objRet->state = 1;
    		$objRet->msg = '参数错误，请重新操作.';
    	
    		return json_encode( $objRet );
    	}
        
        //-----------------
        //由于开发数据库和oss回调之后添加的数据库没在一块  所以注释事务功能
        //-----------------
        //$this->db->begin();
        switch( $type )
        {
//             case ImgBizEnums::MUSEUM_APPLY_PREFIX:
//                 $imgs = new MuseumApplyPics();
//                 $imgs->delbyAssetsId( $operation, $optid );
//             break;
//             case ImgBizEnums::ADMIN_USER_AVATAR_PREFIX:
//                 $imgs = new PriUsersAvatarPics();
//                 $imgs->delbyAssetsId( $operation, $optid );
//             break;
        }
        //$this->db->commit();
        $objRet->state = 0;
    
        echo json_encode( $objRet );
    }
    
    /**
     * 验证图片的宽度和高度
     * @param type $config
     */
    private function checkImage()
    {
        $ret = [];
        if( isset( $_FILES[ 'upfile']['tmp_name']))
        {
            $size = getimagesize($_FILES[ 'upfile']['tmp_name']);
            if( $size )
            {
                if( isset( $_GET[ 'width'] ) && $_GET[ 'width'] < $size[ 1 ] )
                {
                   $ret[ 'state' ] = '宽度超过' . $_GET[ 'width'];
                }
                else if( isset( $_GET[ 'height'] ) && $_GET[ 'height'] < $size[ 0 ] )
                {
                   $ret[ 'state' ] = '高度超过' . $_GET[ 'width'];
                }
            }
        }
        if( $ret )
        {
            echo json_encode( $ret );
            return;
        }
    }
}